import {
    Component, OnInit, HostBinding,
    trigger, transition, animate,
    style, state
} from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Player } from '../http/player';

import { DialogService } from '../dialog.service';

@Component({
    moduleId: module.id,
    template: `
    <div *ngIf="player">
        <h3>"{{ editName }}"</h3>
        <div>
        <label>Id: </label>{{ player._id }}</div>
        <div>
        <label>Name: </label>
        <input [(ngModel)]="editName" placeholder="name"/>
        </div>
        <p>
        <button (click)="save()">Save</button>
        <button (click)="cancel()">Cancel</button>
        </p>
    </div>`,
    animations: [
        trigger('routeAnimation', [
            state('*',
                style({
                    opacity: 1,
                    transform: 'translateX(0)'
                })
            ),
            transition(':enter', [
                style({
                    opacity: 0,
                    transform: 'translateX(-100%)'
                }),
                animate('0.2s ease-in')
            ]),
            transition(':leave', [
                animate('0.5s ease-out', style({
                    opacity: 0,
                    transform: 'translateY(100%)'
                }))
            ])
        ])
    ]
})
export class RouterDetailComponent implements OnInit {
    player: Player;
    editName: string;
    constructor(private route: ActivatedRoute, private router: Router, private dialogService: DialogService) { }

    ngOnInit() {
        this.route.data.subscribe((data: { player: Player }) => {
            this.editName = data.player.name;
            this.player = data.player;
        });
    }
    goBack() {
        let playerId = this.player ? this.player._id : null;
        this.router.navigate(['../../', { id: playerId, foo: 'foo' }], { relativeTo: this.route });
    }
    cancel() {
        this.goBack();
    }

    save() {
        this.player.name = this.editName;
        this.goBack();
    }
    @HostBinding('@routeAnimation') get routeAnimation() {
        return true;
    }
    @HostBinding('style.display') get display() {
        return 'block';
    }
    @HostBinding('style.position') get position() {
        return 'absolute';
    }
    canDeactivate(): Promise<boolean> | boolean {
        // Allow synchronous navigation (`true`) if no crisis or the crisis is unchanged
        if (!this.player || this.player.name === this.editName) {
            return true;
        }
        // Otherwise ask the user with the dialog service and return its
        // promise which resolves to true or false when the user decides
        return this.dialogService.confirm('Discard changes?');
    }
}